from mqttdemo.mqtt1.mqttutil import MqttCallback, MqttUtil


class MyMqttCallback(MqttCallback):
    def on_connect(self, client, userdata, flags, rc):
        if rc == 0:
            print("Custom Callback: Connected to MQTT Broker")
            client.subscribe("custom/topic")
        else:
            print(f"Connection failed with code {rc}")

    def on_message(self, client, userdata, msg):
        print(f"[Custom] Received message: {msg.payload.decode()} on topic {msg.topic}")


# 使用自定义回调
callback = MyMqttCallback()
mqtt_client = MqttUtil("localhost", callback=callback)
mqtt_client.connect()
mqtt_client.loop_start()

try:
    while True:
        pass
except KeyboardInterrupt:
    mqtt_client.loop_stop()
    mqtt_client.disconnect()
